package com.example.design.threadLocaldemo;

import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 自定义线程池 + 反射，解决跨线程传输数据问题
 */
@Slf4j
public class CustomizeThreadPoolExecutor extends ThreadPoolExecutor {
    public CustomizeThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }
    public CustomizeThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }
    public CustomizeThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    }
    public CustomizeThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }
    @Override
    public void execute(Runnable command) {
        // 反射获取当前线程的ThreadLocal
        Map<ThreadLocal, Object> threadLocalMap = ThreadLocalUtil.getThreadLocalMap();
        super.execute(()->{
            for (ThreadLocal tl : threadLocalMap.keySet()) {
                Object value = threadLocalMap.get(tl);
                ThreadLocal newThreadLocal = new ThreadLocal();
                newThreadLocal.set(value);
            }
            try {
                command.run();
            } catch (Exception e) {

            } finally {
                ThreadLocalUtil.resetThreadLocals(ThreadLocalUtil.getThreadLocalMap());
            }
        });
    }
}
